import base from "./base.controller";
import moment from "moment";
import uuid from "node-uuid";
import fs from "fs-promise";
import md5 from "md5";

export default class extends base {

    async _initialize() {
        await super._initialize();
    }

    async gallery() {
        const p = this.query.page || 1;
        let Picture = this.model('admin/Picture');
        let result = await Picture.findPage({
            page: p,
            pageSize: 10
        }, '', {}, {}, {updatedAt: 'desc'}, function (error, results) {
            // this.logger.debug(results);
        });

        await this.render('admin/picture/gallery', {
            records: result.data,
            pager: this.ajaxPage(p, result.pagination.rowCount, result.pagination.pageSize, 'get_page')
        });
    }

    async gallery_table() {
        const p = this.query.page || 1;
        let Picture = this.model('admin/Picture');
        let result = await Picture.findPage({
            page: p,
            pageSize: 12
        }, '', {}, {}, {updatedAt: 'desc'}, function (error, results) {
            // console.log(results);
        });

        await this.render('admin/picture/gallery_table', {
            records: result.data,
            pager: this.ajaxPage(p, result.pagination.rowCount, result.pagination.pageSize, 'get_page')
        });
    }

    async delete() {
        const id = this.post.id || "";
        const ids = id.split(',');

        for (const i in ids) {
            const Picture = this.model('admin/Picture');
            const entity = await  Picture.findById(ids[i]);
            if (entity && entity.storage === "local") {
                let path = `www/public/uploads/${entity.savePath}${entity.saveName}`;
                // console.log(path);
                try{
                    if (await fs.exists(path)) {
                        await fs.unlink(path, function (err) {
                            this.logger.error(err);
                        });
                    }
                }catch(err){
                    this.logger.error(err);
                    // console.log(err);
                }

                entity.remove();
                this.success('删除成功');
                return;
            }else if (entity && entity.storage === "qiniu") {
                //云存储要删除云上的文件，需要调用SDK删除
                // Picture.findByIdAndRemove(ids[i]);
                this.error('不能删除云存储上的文件');
                return;
            }
        }

        this.error('删除失败');

    }

    async add() {

        const files = this.file;
        let Model = this.model('admin/Picture');
        for (let i in files) {
            const file = files[i];

            const result = await Model.uploadImage(file);
            if (result){
                this.json('/admin/picture/gallery','保存成功');
                console.log("image upload success!");
            } else {
                this.json('/admin/picture/gallery', '保存失败');
                console.log("upload image fail!");
            }

            // let ext = '';  //后缀名
            // switch (file.type) {
            //     case 'image/pjpeg':
            //         ext = 'jpg';
            //         break;
            //     case 'image/jpeg':
            //         ext = 'jpg';
            //         break;
            //     case 'image/png':
            //         ext = 'png';
            //         break;
            //     case 'image/x-png':
            //         ext = 'png';
            //         break;
            // }
            // const savepath = moment().format('YYYY-MM-DD') + '/';
            // const savename = uuid.v1() + '.' + ext;
            //
            // //计算md5校验值，如果相同则不保存新的
            // let buf = await fs.readFile(file.path);
            // let checksum_md5 = md5(buf);
            // let Model = this.model('admin/Picture');
            // if (await Model.findOne({md5: checksum_md5})) {
            //     //existed the same file
            //     await fs.unlink(file.path);
            //     this.json('/admin/picture/gallery','文件已经存在');
            // } else {
            //     const err = await fs.move(file.path, 'www/public/uploads/' + savepath + savename);
            //     if (!err) {
            //         const data = {
            //             name: file.name,
            //             ext: ext,
            //             fileType: file.type,
            //             saveName: savename,
            //             savePath: savepath,
            //             storage: 'local',
            //             md5: checksum_md5
            //         };
            //
            //         await Model.saveOrUpdate(data);
            //         this.json('/admin/picture/gallery','保存成功');
            //         console.log("success!");
            //     } else {
            //         this.json('/admin/picture/gallery','保存失败');
            //         console.log("fail!");
            //     }
            // }
        }
    }

    async index() {
        await this.render('admin/picture/index', {
            storages: [{key: 'local', title: '本地存储'}, {key: 'qiniu', title: '七牛云存储'}]
        });
    }

    /**
     * 加载数据表模板，生成HTML返回给前端展示
     * @returns {Promise<void>}
     */
    async table() {
        const p = this.query.page || 1;
        const post = this.post;
        const id = post.id.trim();
        const storage = post.storage.trim();
        const keywords = post.keywords.trim();

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {name: {$regex: keywords, $options: "$i"}},
                    {saveName: {$regex: keywords, $options: "$i"}},
                    {savePath: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (storage !== "") {
            queryParams = Object.assign(queryParams, {storage: storage});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: koahub.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error('没找到符合条件的记录');
                return;
            }
        }


        console.log(`search queryParams:${JSON.stringify(queryParams)}`);

        const pageSize= await this.common.config('LIST_ROWS');
        let Picture = this.model('admin/Picture');
        let result = await Picture.findPage({
            page: p,
            pageSize: pageSize
        }, '', queryParams, {}, {_id: 'desc'}, function (error, results) {
            // console.log(results);
        });

        await this.render('admin/picture/table', {
            records: result.data,
            pager: this.common.ajaxPage(p, result.pagination.rowCount, result.pagination.pageSize, 'get_page')
        });
    }


}
